﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;

namespace Anno.DynamicApi
{
    public static class ApiHelper
    {
        static JsonSerializerSettings serializerSettings = new JsonSerializerSettings
        {
            // 设置为驼峰命名
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), //小驼峰命名法
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };
        static JsonSerializerSettings serializerSettingsDate = new JsonSerializerSettings
        {
            // 设置为驼峰命名
            //ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), //小驼峰命名法
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="IsCamelCaseNames">返回结果是否为驼峰命名</param>
        /// <returns></returns>
        public static HttpResponseMessage ToJson(this object obj, bool IsCamelCaseNames = false)
        {
            string str = "";
            if (obj is String || obj is Char)
            {
                str = obj.NullToStr();
            }
            else
            {
                str = JsonConvert.SerializeObject(obj, Formatting.Indented, IsCamelCaseNames ? serializerSettings : serializerSettingsDate);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.UTF8, "application/json") };
            return result;
        }

        /// <summary>
        /// 驼峰命名JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage ToCamelCaseJson(this object obj)
        {
            return ToJson(obj,true);
        }

    }
}